package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws IOException {
        WmUser user = WmThreadLocalUtil.getUser();
        if(null == user){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String fileName = UUID.randomUUID().toString().replace("-","");
        String sub = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String url = fileStorageService.uploadImgFile("",fileName + sub,multipartFile.getInputStream());

        WmMaterial entity = new WmMaterial();
        entity.setCreatedTime(new Date());
        entity.setIsCollection((short)0);
        entity.setType((short)0);

        entity.setUserId(user.getId());
        entity.setUrl(url);

        wmMaterialMapper.insert(entity);
        return ResponseResult.okResult(entity);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 检查是否合法
        dto.checkParam();

        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        // 添加
        if(dto.getIsCollection() != null){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        WmUser wmUser = WmThreadLocalUtil.getUser();
        if(null == wmUser){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.eq(WmMaterial::getUserId,wmUser.getId());

        wmMaterialMapper.selectPage(page,queryWrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());

        return result;
    }

    /**
     * 根据ID删除图片素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteImageById(Integer id) {
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().in(WmNewsMaterial::getMaterialId, id));
        if(wmNewsMaterials != null && wmNewsMaterials.size() >0 ){
            throw new CustomException(AppHttpCodeEnum.CHANNEL_CITED);
        }

        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if(wmMaterial == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = wmMaterial.getUrl();
        // 删除minio当中的数据
        fileStorageService.delete(url);

        wmMaterialMapper.delete(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId,id));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据ID取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollectById(Integer id) {
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if(wmMaterial == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        wmMaterial.setIsCollection((short)0);
        wmMaterialMapper.updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 根据ID 收藏数据
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectById(Integer id) {
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if(wmMaterial == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        wmMaterial.setIsCollection((short)1);
        wmMaterialMapper.updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }
}
